//
//  HKYResponseProvider.swift
//  HKYHttpRequest
//
//  Created by SHANGLU on 16/12/14.
//  Copyright © 2016年 hky.me. All rights reserved.
//

import UIKit

import RxSwift
//HKYResponseProvider 泛型类型 实际类型为Target 并且遵守HKYRequestTargetProtocol协议
class HKYResponseProvider<Target:HKYRequestTargetProtocol> {
    
    
}

extension HKYResponseProvider {
    
    /**
     请求数据
     
     - parameter target: 参数
     
     - returns: 返回对象
     */
    func requestJSON(target:Target) ->Observable<ResponseJSON>{
        
        return Observable.create({ (observer) -> Disposable in
            
            let request = HKYHttpRequest<Target>().request(target)
            
            request.responseJSON(completionHandler: { (response) in
                if let error = response.result.error {
                    observer.onError(error) //http网络请求错误
                }else{
                    //验证服务器错误
                    let errorRes:HKYException.HttpError =  HKYHttpResponseHelper.isResponseError(response.response)
                    switch errorRes{
                    case.Response200:
                        observer.onNext(response)
                        observer.onCompleted()
                        break
                    default:
                        print(errorRes)
                        break
                    }
                }
            })
            return AnonymousDisposable{
                request.cancel()
            }
        })
    }
    
    
}
